import os
import shutil
from xml.etree import ElementTree as ET

from xml.etree.ElementTree import SubElement

ANDROID_NS = 'http://schemas.android.com/apk/res/android'


def IsExists(file):
    if os.path.exists(file):
        return True
    else:
        print(file, "不存在")
        return False


def copyFile(input, output):
    shutil.copyfile(input, output)


def create_app_name(string_xml, name):
    string_xml_file = ET.parse(string_xml)
    string_root = string_xml_file.getroot()
    string_nodes = string_root.findall('string')
    for string_node in string_nodes:
        app_name_node = string_root.find('string[@name="app_name"]')
        if app_name_node is None:
            app_name_node = SubElement(string_root, 'string')
            app_name_node.set('name', 'app_name')
            app_name_node.text = name
        else:
            app_name_node.text = name
        break
    string_xml_file.write(string_xml, 'UTF-8')


def change_app_pack_name(path, name, direction, pathName):
    # ET.register_namespace('android', ANDROID_NS)
    # manifest_xml_file = ET.parse(path)
    # manifest_root = manifest_xml_file.getroot()
    # old_pack_name = manifest_root.attrib.get('package')
    # print('旧包名', old_pack_name)
    f = open(path, 'r+')
    data = f.read()
    if "landscape" in data:
        data = data.replace('landscape', direction)
    else:
        data = data.replace('portrait', direction)
        # data = data.replace(old_pack_name, name)
    pathList = get_startup_activity(path).split('.')
    pathList[4] = ''
    pathOld = '.'.join(pathList)
    pathList[3] = pathName
    pathNew = '.'.join(pathList)
    data = data.replace(pathOld[0:len(pathOld) - 1], pathNew[0:len(pathNew) - 1])
    f = open(path, 'w+')
    f.write(data)
    f.close()


def change_path(PackPath, name):
    if os.path.isdir(PackPath):
        old_dir_name = os.listdir(PackPath)[0]
        if old_dir_name:
            os.rename(PackPath + '\\' + old_dir_name, PackPath + '\\' + name)
            smali_list = os.listdir(PackPath + '\\' + name)
            for index in smali_list:
                change_dir_path = PackPath + '\\' + name + '\\' + index
                f = open(change_dir_path, 'r+')
                data = f.read()
                if old_dir_name in data:
                    data = data.replace(old_dir_name, name)
                    f = open(change_dir_path, 'w+')
                    f.write(data)
                    f.close()
    else:
        print('该文件路径不存在')


def change_kfzs_pack_name(path, pack):
    f = open(path, 'r+')
    flist = f.readlines()
    flist[0] = 'game_package_name=' + pack + '\n'
    f = open(path, 'w+')
    f.writelines(flist)
    f.close()


def get_startup_activity(manifestFile):
    ET.register_namespace('android', ANDROID_NS)
    key = '{' + ANDROID_NS + '}name'
    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    applicationNode = targetRoot.find('application')
    if applicationNode is None:
        return
    if applicationNode is not None:
        activityLsNode = applicationNode.findall('activity')
    if activityLsNode is None:
        return
    activityName = ''
    for activityNode in activityLsNode:
        bMainActivity = False
        intentLsNode = activityNode.findall('intent-filter')
        if intentLsNode is None:
            return
        for intentNode in intentLsNode:
            bFindAction = False
            bFindCategory = False
            actionLsNode = intentNode.findall('action')
            for actionNode in actionLsNode:
                if actionNode.attrib[key] == 'android.intent.action.MAIN':
                    bFindAction = True
                    break

            if not bFindAction:
                continue
            categoryLsNode = intentNode.findall('category')
            for categoryNode in categoryLsNode:
                if categoryNode.attrib[key] == 'android.intent.category.LAUNCHER':
                    bFindCategory = True
                    break

            if bFindAction and bFindCategory:
                bMainActivity = True
                break

        if bMainActivity:
            activityName = activityNode.attrib[key]
            break
    return activityName
